# -*- coding:utf8 -*-
import urllib
import urllib2
from wanbatvapp.http.whttp import send_error_response_on_exception, send_response_with_result

__author__ = 'Forcs'

def send_bind_message(app_pkg=None, client=None, group=None, api_tag=None):
    from wanpuzzle.models.common import Application
    try:
        app_model = Application.objects.get(package=app_pkg)
    except Exception as e:
        return send_error_response_on_exception(e)

    post_data = dict()
    post_data["app"] = app_model.token + "_" + app_model.sign_key
    post_data["client"] = client
    post_data["group"] = group
    post_data["api"] = api_tag

    from wanbatvapp.settings import MESSENGER_HOST
    req = urllib2.Request('http://%s/posthouse/bind' % MESSENGER_HOST, data=urllib.urlencode(post_data))
    res = urllib2.urlopen(req)
    content = res.read()
    res.close()

    return send_response_with_result(content)

def send_binds_message(app_pkg=None, client=None, groups=None, api_tag=None):
    from wanpuzzle.models.common import Application
    try:
        app_model = Application.objects.get(package=app_pkg)
    except Exception as e:
        return send_error_response_on_exception(e)

    post_data = dict()
    post_data["app"] = app_model.token + "_" + app_model.sign_key
    post_data["client"] = client
    post_data["groups"] = groups
    post_data["api"] = api_tag

    from wanbatvapp.settings import MESSENGER_HOST
    req = urllib2.Request('http://%s/posthouse/binds' % MESSENGER_HOST, data=urllib.urlencode(post_data))
    res = urllib2.urlopen(req)
    content = res.read()
    res.close()

    return send_response_with_result(content)